import random
import math
import tkinter as tk
from tkinter import Canvas

# 常量定义（增强可读性与扩展性）
CANVAS_WIDTH = 800
CANVAS_HEIGHT = 600
CANVAS_CENTER_X = CANVAS_WIDTH / 2
CANVAS_CENTER_Y = CANVAS_HEIGHT / 2
IMAGE_ENLARGE = 12
HEART_COLORS = ['#FF69B4', '#FF1493', '#FFC0CB', '#FFB6C1']  # 多色爱心渐变
FPS = 60
ANIMATION_DURATION = 30  # 动画周期（帧）


def heart_function(t, shrink_ratio=IMAGE_ENLARGE):
    """爱心参数方程生成器，优化计算精度"""
    x = 16 * (math.sin(t) ** 3)
    y = -(13 * math.cos(t) - 5 * math.cos(2 * t) - 2 * math.cos(3 * t) - math.cos(4 * t))
    x *= shrink_ratio
    y *= shrink_ratio
    x += CANVAS_CENTER_X
    y += CANVAS_CENTER_Y
    return int(x), int(y)


def scatter_inside(x, y, beta=0.15):
    """随机内部扩散，优化随机性分布"""
    ratio_x = -beta * math.log(random.random())
    ratio_y = -beta * math.log(random.random())
    dx = ratio_x * (x - CANVAS_CENTER_X)
    dy = ratio_y * (y - CANVAS_CENTER_Y)
    return x - dx, y - dy


def shrink(x, y, ratio):
    """抖动效果，增强边缘动态感"""
    force = -1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.6)
    dx = ratio * force * (x - CANVAS_CENTER_X)
    dy = ratio * force * (y - CANVAS_CENTER_Y)
    return x - dx, y - dy


def curve(p):
    """自定义曲线函数，优化动画节奏"""
    return 2 * (2 * math.sin(4 * p)) / (2 * math.pi)


class EnhancedHeart:
    """增强版爱心类：多色渐变、粒子爆炸、交互响应"""

    def __init__(self, generate_frame=ANIMATION_DURATION):
        self._points = set()  # 原始爱心轮廓点
        self._edge_diffusion = set()  # 边缘扩散点
        self._center_diffusion = set()  # 中心扩散点
        self.all_frames = {}  # 每帧动态数据
        self.halo_points = set()  # 光环点
        self.build(2500)  # 增加粒子数量，让爱心更饱满
        self.generate_frame = generate_frame
        for frame in range(generate_frame):
            self.calc(frame)

    def build(self, number):
        # 生成爱心轮廓
        for _ in range(number):
            t = random.uniform(0, 2 * math.pi)
            x, y = heart_function(t)
            self._points.add((x, y))
        # 边缘扩散层
        for x, y in list(self._points):
            for _ in range(4):  # 增加扩散密度
                nx, ny = scatter_inside(x, y, 0.08)
                self._edge_diffusion.add((nx, ny))
        # 中心扩散层
        point_list = list(self._points)
        for _ in range(5000):  # 大幅增加中心粒子
            x, y = random.choice(point_list)
            nx, ny = scatter_inside(x, y, 0.2)
            self._center_diffusion.add((nx, ny))

    @staticmethod
    def calc_position(x, y, ratio):
        """优化位置计算，增加随机抖动"""
        force = 1 / (((x - CANVAS_CENTER_X) ** 2 + (y - CANVAS_CENTER_Y) ** 2) ** 0.520)
        dx = ratio * force * (x - CANVAS_CENTER_X) + random.randint(-2, 2)
        dy = ratio * force * (y - CANVAS_CENTER_Y) + random.randint(-2, 2)
        return x - dx, y - dy

    def calc(self, generate_frame):
        """每帧动画计算：多色渐变、光环缩放、粒子爆炸"""
        ratio = 10 * curve(generate_frame / ANIMATION_DURATION * math.pi)
        halo_radius = int(5 + 8 * (1 + curve(generate_frame / ANIMATION_DURATION * math.pi)))
        halo_number = int(3500 + 5000 * abs(curve(generate_frame / ANIMATION_DURATION * math.pi) ** 2))
        frame_points = []

        # 1. 生成彩色光环
        self.halo_points.clear()
        for _ in range(halo_number):
            t = random.uniform(0, 2 * math.pi)
            x, y = heart_function(t, shrink_ratio=12.2)
            x, y = shrink(x, y, halo_radius)
            if (x, y) not in self.halo_points:
                self.halo_points.add((x, y))
                x += random.randint(-18, 18)
                y += random.randint(-18, 18)
                size = random.choice((1, 2, 3))
                color = random.choice(HEART_COLORS)
                frame_points.append((x, y, size, color))

        # 2. 生成彩色轮廓
        for x, y in self._points:
            x, y = self.calc_position(x, y, ratio)
            size = random.randint(2, 4)
            color = random.choice(HEART_COLORS)
            frame_points.append((x, y, size, color))

        # 3. 生成彩色边缘扩散
        for x, y in self._edge_diffusion:
            x, y = self.calc_position(x, y, ratio)
            size = random.randint(1, 3)
            color = random.choice(HEART_COLORS)
            frame_points.append((x, y, size, color))

        # 4. 生成彩色中心扩散
        for x, y in self._center_diffusion:
            x, y = self.calc_position(x, y, ratio)
            size = random.randint(1, 2)
            color = random.choice(HEART_COLORS)
            frame_points.append((x, y, size, color))

        self.all_frames[generate_frame] = frame_points

    def render(self, canvas, frame):
        """渲染每帧：彩色粒子+平滑动画"""
        for x, y, size, color in self.all_frames[frame % self.generate_frame]:
            canvas.create_rectangle(
                x, y, x + size, y + size,
                width=0,
                fill=color
            )


def draw_loop(root, canvas, heart, frame=0):
    """优化渲染循环，提升帧率稳定性"""
    canvas.delete('all')
    heart.render(canvas, frame)
    root.after(int(1000 / FPS), draw_loop, root, canvas, heart, frame + 1)


if __name__ == '__main__':
    root = tk.Tk()
    root.title("炫彩动态爱心")
    root.resizable(False, False)  # 固定窗口大小
    canvas = Canvas(
        root,
        bg='black',
        height=CANVAS_HEIGHT,
        width=CANVAS_WIDTH,
        highlightthickness=0  # 移除边框
    )
    canvas.pack()


    # 绑定交互：点击屏幕重新生成爱心
    def reset_heart(event):
        global heart
        heart = EnhancedHeart()


    canvas.bind('<Button-1>', reset_heart)

    heart = EnhancedHeart()
    draw_loop(root, canvas, heart)
    root.mainloop()